package com.zdkj.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdkj.admin.api.entity.SysLog;
import com.zdkj.admin.api.vo.PreLogVo;
import com.zdkj.admin.mapper.SysLogMapper;
import com.zdkj.admin.service.SysLogService;
import com.zdkj.common.core.constant.CacheConstants;
import com.zdkj.common.core.constant.CommonConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 日志表 服务实现类
 * </p>
 *
 * @author cui_com
 * @since 2017-11-20
 */
@Service
public class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog> implements SysLogService {

    /**
     * 默认系统日志保存时间 一个月
     */
    private static final Integer SYS_LOG_DEFAULT_EXPIRE_TIME = 30 * 24 * 60 * 60;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SysLogMapper sysLogMapper;

    /**
     * 批量插入前端错误日志
     *
     * @param preLogVoList 日志信息
     * @return true/false
     */
    @Override
    public Boolean saveBatchLogs(List<PreLogVo> preLogVoList) {
        List<SysLog> sysLogs = preLogVoList.stream()
                .map(pre -> {
                    SysLog log = new SysLog();
                    log.setType(CommonConstants.STATUS_LOCK);
                    log.setTitle(pre.getInfo());
                    log.setException(pre.getStack());
                    log.setParams(pre.getMessage());
                    log.setCreateTime(LocalDateTime.now());
                    log.setRequestUri(pre.getUrl());
                    log.setCreateBy(pre.getUser());
                    return log;
                })
                .collect(Collectors.toList());
        return this.saveBatch(sysLogs);
    }

    @Override
    public int deleteExpireLogs() {
        Integer expireTimeSeconds = this.getExpire();
        return sysLogMapper.deleteExpireLog(expireTimeSeconds);
    }

    @Override
    public int fileExpireLog() {
        return sysLogMapper.fileExpireLog(getExpire());
    }

    @Override
    public Integer getExpire() {
        Integer expireTime = (Integer) redisTemplate.opsForValue().get(CacheConstants.SYS_LOG_EXPIRE_TIME_SECOND);
        return (expireTime == null || expireTime == 0) ? SYS_LOG_DEFAULT_EXPIRE_TIME : expireTime;
    }

    @Override
    public void setExpire(Integer timeSecond) {
        redisTemplate.opsForValue().set(CacheConstants.SYS_LOG_EXPIRE_TIME_SECOND, timeSecond);
    }
}
